<aside class="right-side">                
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>Quản lý
            <small>Thu chi hàng ngày</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i>Trang chủ</a></li>
           <li class="active">Thu chi hàng ngày</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12"> 
                <div class="box">
                    <div class="box-header">
                        <h3 class="box-title">Thu chi hàng ngày</h3>                     
                    </div>
                    <div class="box-body table-responsive">
                        <div id="example1_wrapper" class="dataTables_wrapper form-inline" role="grid">

                            <table id="example1" class="table table-bordered table-hover dataTable" aria-describedby="example1_info">
                            <thead>
                                <tr role="row"><th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending" style="width: 172px;">Ngày (dd/mm/yyyy)</th><th class="sorting" role="columnheader" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending" style="width: 251px;">Tổng thu</th><th class="sorting" role="columnheader" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending" style="width: 230px;">Tổng chi</th><th class="sorting" role="columnheader" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Engine version: activate to sort column ascending" style="width: 147px;"></th></tr>
                            </thead>
                            
                        <tbody role="alert" aria-live="polite" aria-relevant="all">
                            <?php if(count($daily_reports) > 0) {
                                foreach ($daily_reports as $dlrp) { ?>
                                    <tr id="<?php echo $dlrp->id;?>">
                                        <td class=" sorting_1"><a href="<?php echo base_url();?>daily_report_detail/index/<?php echo $dlrp->id;?>"><?php echo date("d/m/Y", strtotime($dlrp->created));?></a></td>
                                        <td class=" "><?php echo $dlrp->earn_total;?></td>
                                        <td class=" "><?php echo $dlrp->spend_total;?></td>
                                        <td><button onclick="add()" class="btn btn-primary btn-flat">Thêm</button>&nbsp;&nbsp;<button onclick="edit(<?php echo $dlrp->id; ?>)" class="btn btn-info btn-flat">Sửa</button>&nbsp;&nbsp;<button onclick="delete_row(<?php echo $dlrp->id; ?>)" class="btn btn-danger btn-flat">Xóa</button></td>
                                    </tr>
                                <?php }} else { ?>
                                    <tr id="null">
                                    <td class=" sorting_1">Không có dữ liệu</td>
                                    <td class=" "></td>
                                    <td class=" "></td>
                                    <td><button onclick="add()" class="btn btn-primary btn-flat">Thêm</button>&nbsp;&nbsp;<button class="btn btn-info btn-flat" disable>Sửa</button>&nbsp;&nbsp;<button class="btn btn-danger btn-flat" disable>Xóa</button></td>
                                </tr>
                                <?php } ?>
                            </tbody></table>
                        </div>
                    </div><!-- /.box-body -->
                </div><!-- /.box -->
            </div>
        </div>
    </section><!-- /.content -->
</aside>

<script type="text/javascript">

    function isValidDate(s) {
        // format D(D)/M(M)/(YY)YY
        var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

        if (dateFormat.test(s)) {
            // remove any leading zeros from date values
            s = s.replace(/0*(\d*)/gi,"$1");
            var dateArray = s.split(/[\.|\/|-]/);
          
            // correct month value
            dateArray[1] = dateArray[1]-1;

            // correct year value
            if (dateArray[2].length<4) {
                // correct year value
                dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
            }

            var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
            if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    //get base url;
    var base_url = '<?php echo base_url();?>';
    
    //------------------------------- add data row -----------------------------------
    function add () {
        var newRow = '<tr id="new_row"><td><input'
            + ' type="text" id="created" class="form-control"/></td>' 
            + '<td>0</td>'
            + '<td>0</td>'
            + '<td><button onclick="ok_add()"'
            + 'class="btn btn-primary btn-flat">Đồng ý' 
            + '</button>&nbsp;&nbsp;<button onclick="cancle_add()"'
            + 'class="btn btn-danger btn-flat">Hủy</button>'
            + '</td></tr>';
        $('#example1 > tbody > tr:first').before(newRow);
    }

    function ok_add() {

        //get value from input has id = name
        var created_value = $('input#created').val();

        if(!created_value) {
            alert("Ngày không được để trống");
            return false;
        }else {
            if(!isValidDate(created_value)) {
               alert("Ngày không đúng");
               return false; 
            }
        }

        //data to submit
        var daily_report = {
            created : created_value,
            earn_total : 0,
            spend_total : 0
        };

        $.ajax({
         type: "POST",
         url: base_url + "daily_report/add_new", 
         data: daily_report,
         dataType: "text",  
         cache : false,
         success: 
              function(json){
                alert('Thêm thành công!!!');
                var obj = jQuery.parseJSON(json);

                //add data row to database
                var dataRow = [
                    '<a href="' + base_url + 'daily_report_detail/index/' + obj['id'] +'">' + created_value + '</a>',
                    0,
                    0,
                    '<button id="' + obj['id'] + '" onclick="add()"'
                    + 'class="btn btn-primary btn-flat">Thêm</button>&nbsp;&nbsp;'
                    + '<button onclick="edit(' + obj['id'] + ')"'
                    + 'class="btn btn-info btn-flat">Sửa</button>&nbsp;&nbsp;'
                    + '<button onclick="delete_row(' + obj['id'] + ')"'
                    + 'class="btn btn-danger btn-flat">Xóa</button>'
                ];

                //add row to data table
                var t = $('#example1').DataTable();
                
                t.row('#null').remove().draw();
                t.row.add(dataRow).draw();

                //add id for new row
                $('button#' + obj['id']).parent().parent().attr('id', obj['id']);
              },
        error: function() {
                alert('Thêm thất bại!!!');
                $('#example1 >tbody').find('tr#null').hide();
                $('#example1 >tbody').find('tr#new_row').remove();
            }
        });
    }

    function cancle_add() {
        $('#example1 >tbody >tr:first').remove();
    }

    //---------------- end add datarow ---------------------------------------------
     
    //----------------- edit row ---------------------------------------------------    
    //edit data row
    function edit(id) {
        var created_value = $('tr#' + id + ' > td:first').text();
        var earn_total = $('tr#' + id + ' > td:nth-child(2)').text();
        var spend_total = $('tr#' + id + ' > td:nth-child(3)').text();

        var newRow = '<tr id="new_row"><td><input'
            + ' type="text" id="created" class="form-control" value="' + created_value +'"/>'
            + '</td><td>' + earn_total +'</td><td>' + spend_total + '</td>'
            + '<td><button onclick="ok_edit(' + id + ')"'
            + 'class="btn btn-primary btn-flat">Đồng ý' 
            + '</button>&nbsp;&nbsp;<button onclick="cancle_edit(' + id + ')"'
            + 'class="btn btn-danger btn-flat">Hủy</button>'
            + '</td></tr>';

        $('#example1 > tbody').find('tr#' + id).hide();    
        $('#example1 > tbody > tr#' + id).before(newRow);
    }

    //ok edit
     function ok_edit(id) {
        //get value from input has id = name
        var created_value = $('input#created').val();

        if(!created_value) {
            alert("Ngày không được để trống");
            return false;
        }else {
            if(!isValidDate(created_value)) {
               alert("Ngày không đúng");
               return false; 
            }
        }

        //data to submit
        var daily_report = {
            id : id,
            created : created_value
        };

        $.ajax({
         type: "POST",
         url: base_url + "daily_report/edit", 
         data: daily_report,
         dataType: "text",  
         cache : false,
         success: 
              function(json){
                alert('Cập nhật thành công!!!');

                //add data row to database
                var dataRow = [
                    '<a href="' + base_url + 'daily_report_detail/index/' + id +'">' + created_value + '</a>',
                    0,
                    0,
                    '<button id="' + id + '" onclick="add()"'
                    + 'class="btn btn-primary btn-flat">Thêm</button>&nbsp;&nbsp;'
                    + '<button onclick="edit(' + id + ')"'
                    + 'class="btn btn-info btn-flat">Sửa</button>&nbsp;&nbsp;'
                    + '<button onclick="delete_row(' + id + ')"'
                    + 'class="btn btn-danger btn-flat">Xóa</button>'
                ];

                //add row to data table
                var t = $('#example1').DataTable();
                //remove old data
                t.row('#' + id).remove().draw();
                t.row.add(dataRow).draw();

                //add id for new row
                $('button#' + id).parent().parent().attr('id', id);
              },
        error: function() {
                alert('Cập nhật thất bại!!!');
                $('#example1 >tbody').find('tr#new_row').remove();
            }
        });
    }   

    function cancle_edit (id) {
        $('#example1 > tbody').find('tr#new_row').remove();    
        $('#example1 > tbody > tr#' + id).show();
    }

    //-------------------------------- end edit ----------------------------------
    //-------------------------------- delete -----------------------------------
    function delete_row (id) {
        if (confirm('Bạn có muốn xóa, thao tác này không thể phục hồi?')) {
            //data to submit
            var daily_report = {
                id : id
            };

            $.ajax({
             type: "POST",
             url: base_url + "daily_report/delete", 
             data: daily_report,
             dataType: "text",  
             cache : false,
             success: 
                  function(json){
                    alert('Xóa thành công!!!');

                    //add row to data table
                    var t = $('#example1').DataTable();

                    //check if database has no row
                    if($('#example1 > tbody').children('tr').length == 1) {
                        var dataRow = [
                            'Không có dữ liệu',
                            '',
                            '',
                            '<button onclick="add()" class="btn btn-primary btn-flat">Thêm'
                            + '</button>&nbsp;&nbsp;<button class="btn btn-info btn-flat"'
                            + ' disable>Sửa</button>&nbsp;&nbsp;<button '
                            + ' class="btn btn-danger btn-flat" disable>Xóa</button>'
                        ];
                        t.row.add(dataRow).draw();

                        //remove old data
                        t.row('#' + id).remove().draw();

                        //add id for new row
                        $('#example1 >tbody>tr:first').attr('id', 'null');
                    }
                    //remove old data
                    t.row('#' + id).remove().draw();

                  },
            error: function() {
                    alert('Xóa thất bại!!!');
                }
            });
        }
    }
    
</script>
